import request from '@/utils/request'
import {setToken} from '@/utils/auth'
import Keycloak from 'keycloak-js';
import router from '../../router'

let initOptions = {
  url: 'http://192.168.137.100:8080/auth',
  realm: 'test',
  clientId: 'vue',
  onLoad: 'login-required',
  enableLogging : true
}

const keycloak = Keycloak(initOptions);
let authenticated = false;

export function initKeycloak(){
  keycloak.init({onLoad: initOptions.onLoad }).then((auth) => {
    if (!auth) {
      window.location.reload();
    } else {
      request({
        url: '/login',
        headers: {
          Authorization: 'Bearer ' + keycloak.token
        },
        method: 'post',
      }).then((res) => {
        setToken(res.token);
        authenticated = true;
        router.push({path: ''}).then(r =>{
          console.log("login success")
        }).catch((res)=>{

        });
      }).catch((res) => {
      });
    }

    //Token Refresh
    setInterval(() => {
      keycloak.updateToken(70).then((refreshed) => {
        if (refreshed) {
          //更新token
          setToken(keycloak.token);
          console.log('Token refreshed' + refreshed);
        } else {
          console.log('Token not refreshed, valid for '
            + Math.round(keycloak.tokenParsed.exp + keycloak.timeSkew - new Date().getTime() / 1000) + ' seconds');
        }
      }).catch(() => {
        console.log('Failed to refresh token');
      });
    }, 6000)

  }).catch(() => {
    console.log("Authenticated Failed");
  });
}

export function keycloakLogout() {
  keycloak.logout("/login");
}

export function isAuthenticated() {
  return authenticated;
}

export default keycloak
